<?php

namespace app\controller;

use think\Config;
use app\service\UserService;

class Auth extends Base
{
    protected $userService;
    
    protected function _initialize()
    {
        parent::_initialize();
        $this->userService = new UserService();
    }
    function testUserId(){
        $user_id = $this->userService->getUserId();
        debug_dump($user_id);
    }
    function testGLogin(){
        $userInfo = [
            'sub' => '1234567890',
            'email' => 'test@test.com',
            'name' => 'Test User',
            'picture' => 'https://example.com/picture.jpg'
        ];
        $result = $this->userService->createOrUpdateGoogleUser(
            $userInfo['sub'],
            $userInfo['email'],
            $userInfo['name'],
            $userInfo['picture']
        );
        debug_dump($result);
    }
    /**
     * Google login callback
     */
    public function googleCallback()
    {
        $code = $this->request->get('code');
        if (empty($code)) {
            $this->error('授權請求無效');
        }
        
        // Get Google Token
        $tokenData = $this->getGoogleToken($code);
        if (!$tokenData) {
            $this->error('無法獲取Google授權令牌');
        }
        
        // Get Google user information
        $userInfo = $this->getGoogleUserInfo($tokenData['access_token']);
        if (!$userInfo) {
            $this->error('無法獲取Google用戶信息');
        }
        
        // Create or update user
        $result = $this->userService->createOrUpdateGoogleUser(
            $userInfo['sub'],
            $userInfo['email'],
            $userInfo['name'],
            $userInfo['picture']
        );
        
        if ($result['status']) {
            $this->redirect('/');
        } else {
            $this->error($result['message']);
        }
    }
    
   
    
    
    
    /**
     * Get Google Token
     * @param string $code Authorization code
     * @return array|false
     */
    protected function getGoogleToken($code)
    {
        $googleConfig = Config::get('app.google');
        
        $clientId = $googleConfig['client_id'];
        $clientSecret = $googleConfig['client_secret'];
        $redirectUri = $this->_domain . '/auth/googleCallback';
        
        $url = 'https://oauth2.googleapis.com/token';
        $data = [
            'code' => $code,
            'client_id' => $clientId,
            'client_secret' => $clientSecret,
            'redirect_uri' => $redirectUri,
            'grant_type' => 'authorization_code'
        ];
        
        $result = $this->httpPost($url, $data);
        return json_decode($result, true);
    }
    
    /**
     * Get Google user information
     * @param string $accessToken Access token
     * @return array|false
     */
    protected function getGoogleUserInfo($accessToken)
    {
        $url = 'https://www.googleapis.com/oauth2/v3/userinfo';
        $headers = ['Authorization: Bearer ' . $accessToken];
        
        $result = $this->httpGet($url, $headers);
        return json_decode($result, true);
    }
    
    /**
     * HTTP POST request
     * @param string $url Request URL
     * @param array $data Request data
     * @param array $headers Request headers
     * @return string
     */
    protected function httpPost($url, $data = [], $headers = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return $response;
    }
    
    /**
     * HTTP GET request
     * @param string $url Request URL
     * @param array $headers Request headers
     * @return string
     */
    protected function httpGet($url, $headers = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return $response;
    }
    
} 